﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SW.EF.DAL;
using SW.EF.DAL.PermissionModuleRepository;

namespace SW.EF.BLL.PermissionModule
{
    public class UserService : BaseService, IUserService
    {
        #region Constructor

        public UserService() { }

        #endregion

        #region Interface Implement

        public void AddUser(User user)
        {
            base.UnitOfWork.UserRepository.Save(user);                  
        }

        public IList<User> GetUsers()
        {
            return base.UnitOfWork.UserRepository.Query().ToList();
        }

        public void RegisterUser(User user, Role role)
        {
            base.UnitOfWork.UserRepository.Save(user, false);
            base.UnitOfWork.RoleRepository.Save(role, false);
            base.UnitOfWork.SaveChanges();
        }

        public bool IsExistUser(string account, string password)
        {
            return base.UnitOfWork.UserRepository.Query().Any(x => x.Account == account && x.Password == password);
        }

        public User GetUser(int id)
        {
            return base.UnitOfWork.UserRepository.Find(id);
        }

        public User GetUser(string account)
        {
            return base.UnitOfWork.UserRepository.Filter(x => x.Account == account).FirstOrDefault();
        }

        public List<Permission> GetModuleCategoryList(bool isAdmin, int userId, List<int> roleIdList)
        {
            if (isAdmin)
                return UnitOfWork.PermissionRepository.Filter(x => x.Deep != 3).ToList();
            var listRolePermission = (
                from i in base.UnitOfWork.PermissionRepository.Query()
                where i.Deep != 3 && i.Roles.All(x => roleIdList.Contains(x.Id))
                select i
                ).ToList();
            var listUserPermission =base.UnitOfWork.UserPermissionRelationRepository.Query().Include(x => x.Permission).Where(x => x.Id == userId && x.Permission.Deep != 3).ToList();
            var listUserExcludePermission = listUserPermission.Where(x => x.State == false).Select(x => x.Permission).ToList();
            var listUserIncludePermission = listUserPermission.Where(x => x.State).Select(x => x.Permission).ToList();
            var listAllUserPermissions = listRolePermission.Union(listUserIncludePermission).ToList();
            listUserExcludePermission.ForEach(r => listAllUserPermissions.Remove(r));
            return listUserExcludePermission;
        }

        #endregion

    }
}


